package com.lzw.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class OSSUtil {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 上传 MultipartFile 文件到阿里云 OSS
     * @param file   前端上传的文件（MultipartFile 类型）
     * @param folder OSS 中的目标文件夹路径
     * @return 文件的 OSS URL
     */
    public String uploadImage(MultipartFile file, String folder) {
        // 创建 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try (InputStream inputStream = file.getInputStream()) {
            // 获取原始文件名，并为其添加唯一标识
            String originalFileName = file.getOriginalFilename();
            String fileName = folder + "/" + UUID.randomUUID().toString() + "_" + originalFileName;

            // 上传文件到 OSS
            ossClient.putObject(bucketName, fileName, inputStream);

            // 返回文件的 URL
            return "https://" + bucketName + "." + endpoint.replace("https://", "") + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        } finally {
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }
    }
}
